package net.luerything.restlet.gwt.rpc.demo;

import com.google.gwt.user.server.rpc.SerializationPolicyLoader;
import net.luerything.restlet.gwt.rpc.*;
import net.luerything.restlet.gwt.rpc.demo.client.DemoService;
import org.restlet.Component;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Directory;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author keke
 */
public class RunDemoServer {
  static String HTML = "<!doctype html><html><body>" +
      "<script src=\"/gwt/gwtrpcrestlet.demo/gwtrpcrestlet.demo.nocache.js\"></script>" +
      "</body></html>";

  public static void main(String[] args) throws Exception {
    Component comp = new Component();
    comp.getServers().add(Protocol.HTTP, 8888);
    comp.getClients().add(Protocol.FILE);
    comp.getClients().add(Protocol.CLAP);
    comp.getDefaultHost().attach("/demo.html", new Restlet() {
      @Override
      public void handle(final Request request, final Response response) {
        super.handle(request, response);
        response.setEntity(new StringRepresentation(HTML, MediaType.TEXT_HTML));
      }
    });
    GwtRpc gwtRpc = new GwtRpcImpl(new DefaultSerializationPolicyProvider(new JseResolver(), new DefaultPolicyLoader()));
    comp.getDefaultHost().attach("/demo.rpc", new DemoRestlet(gwtRpc));
    comp.getDefaultHost().attach("/gwt/", new Directory(comp.getContext().createChildContext(), "clap://class/gwt/"));
    comp.start();
  }

  static class JseResolver implements PolicyFileResolver {

    @Override
    public String getPolicyFileURI(final String moduleBaseName, final String strongName) {
      try {
        String modulePath = new URL(moduleBaseName).getPath();
        return "clap://class" + SerializationPolicyLoader.getSerializationPolicyFileName(modulePath + strongName);
      } catch (MalformedURLException e) {
        return null;
      }

    }
  }

  static class DemoRestlet extends GwtRpcRestlet implements DemoService {
    public DemoRestlet(final GwtRpc gwtRpc) {
      super(gwtRpc);
    }

    @Override
    public String hello(final String name) {
      return "Hello " + name + " !!!";
    }
  }
}
